package dyyx;

import java.util.Date;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZkTest {

	public static void main(String[] args) throws Exception {

		System.out.println("ZkTest," + new Date());
		
		ZooKeeper zooKeeper = ZkUtils.getClient();

		System.out.println(zooKeeper.getState());

		System.out.println(zooKeeper.toString());

		String path = "/zk_test";
		String data = new Date() + "";
		// if the given version is -1, it matches any node's versions
		int version = -1;
		boolean watcher = false;
		boolean delete = false;

		// acl 为 null ,
		// org.apache.zookeeper.KeeperException$MarshallingErrorException:
		// KeeperErrorCode = MarshallingError for /zk_test
		
		Stat stat = zooKeeper.exists(path, watcher);
		System.out.println("exists.stat=" + stat);
		

		try {
			String createResult = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
					CreateMode.PERSISTENT);
			System.out.println("createResult=" + createResult);
		} catch (Throwable e) {
			// org.apache.zookeeper.KeeperException$NodeExistsException:KeeperErrorCode = NodeExists for /zk_test
			System.out.println("create error," + e);
		}
		
		try {
			String createResult = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
					CreateMode.PERSISTENT);
			System.out.println("createResult=" + createResult);
		} catch (Throwable e) {
			// org.apache.zookeeper.KeeperException$NodeExistsException:KeeperErrorCode = NodeExists for /zk_test
			System.out.println("create2 error," + e);
		}

		try {
			stat = zooKeeper.setData(path, data.getBytes(), version);
			System.out.println("stat=" + stat);
		} catch (Throwable e) {
			// org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /zk_test
			System.out.println("setData error," + e);
		}
		stat = new Stat();
		try {
			byte[] bytes = zooKeeper.getData(path, watcher, stat);
			System.out.println("getData.stat=" + stat);
			System.out.println("data=" + new String(bytes));

		} catch (Throwable e) {
			System.out.println("getData error," + e);
		}
		
		stat = zooKeeper.exists(path, watcher);
		System.out.println("exists.stat1=" + stat);
		
		
		System.out.println("delete="+delete);
		
		if (delete) {

			try {
				zooKeeper.delete(path, version);
			} catch (Throwable e) {
				System.out.println("delete error," + e);
			}

			try {
				zooKeeper.delete(path, version);
			} catch (Throwable e) {
				System.out.println("delete error," + e);
			}

		}
		
		try {
			stat = new Stat();
			zooKeeper.getData(path, watcher, stat);
		} catch (Throwable e) {
			System.out.println("getData error," + e);
		}
		
		stat = zooKeeper.exists(path, watcher);
		System.out.println("exists.stat2=" + stat);
		
		Thread.sleep(5000);
		
		zooKeeper.close();
		

	}
}
